package com.xyy.controller;

import com.xyy.common.Result;
import com.xyy.dto.PasswordResetDTO;
import com.xyy.dto.UserLoginDTO;
import com.xyy.dto.UserRegisterDTO;
import com.xyy.entity.User;
import com.xyy.service.UserService;
import com.xyy.service.FileService;
import com.xyy.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
import java.util.HashMap;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private FileService fileService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Map<String, Object>> register(@Valid @RequestBody UserRegisterDTO registerDTO) {
        try {
            Map<String, Object> result = userService.register(registerDTO);
            return Result.success("注册成功", result);
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody UserLoginDTO loginDTO) {
        try {
            Map<String, Object> result = userService.login(loginDTO);
            return Result.success("登录成功", result);
        } catch (Exception e) {
            log.error("用户登录失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 发送邮箱验证码
     */
    @PostMapping("/sendEmailCode")
    public Result<Void> sendEmailCode(@RequestBody Map<String, String> request) {
        try {
            String email = request.get("email");
            String username = request.get("username");
            
            if (email == null || email.trim().isEmpty()) {
                return Result.error("邮箱不能为空");
            }
            
            // 验证用户名和邮箱是否匹配
            if (username != null && !username.trim().isEmpty()) {
                userService.validateUserEmail(username, email);
            }
            
            userService.sendEmailCode(email);
            return Result.success("验证码发送成功", null);
        } catch (Exception e) {
            log.error("发送邮箱验证码失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 密码重置
     */
    @PostMapping("/resetPassword")
    public Result<Void> resetPassword(@Valid @RequestBody PasswordResetDTO resetDTO) {
        try {
            userService.resetPassword(resetDTO);
            return Result.success("密码重置成功", null);
        } catch (Exception e) {
            log.error("密码重置失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public Result<Map<String, Object>> getUserInfo(@RequestHeader("Authorization") String token) {
        try {
            // 这里可以从token中解析用户信息，暂时返回空
            return Result.success("获取用户信息成功", null);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据用户名获取用户信息
     */
    @GetMapping("/getUserInfo")
    public Result<User> getUserInfoByUsername(@RequestParam String username) {
        try {
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }
            return Result.success("获取成功", user);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 根据用户名获取忘记密码时需要的用户信息
     */
    @GetMapping("/getUserInfoForReset")
    public Result<Map<String, Object>> getUserInfoForReset(@RequestParam String username) {
        try {
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 只返回忘记密码时需要的安全信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("username", user.getUsername());
            userInfo.put("email", user.getEmail()); // 返回邮箱，前端可以自动填充
            userInfo.put("hasSecurityQuestions", 
                user.getFavoriteFood() != null && 
                user.getFavoritePlace() != null && 
                user.getFavoriteSchool() != null);
            
            return Result.success("获取成功", userInfo);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 验证密保问题
     */
    @PostMapping("/verifySecurityQuestions")
    public Result<Void> verifySecurityQuestions(@RequestBody Map<String, String> request) {
        try {
            String username = request.get("username");
            String favoriteFood = request.get("favoriteFood");
            String favoritePlace = request.get("favoritePlace");
            String favoriteSchool = request.get("favoriteSchool");
            
            if (username == null || favoriteFood == null || favoritePlace == null || favoriteSchool == null) {
                return Result.error("参数不完整");
            }
            
            boolean isValid = userService.verifySecurityQuestions(username, favoriteFood, favoritePlace, favoriteSchool);
            if (isValid) {
                return Result.success("验证成功", null);
            } else {
                return Result.error("密保问题答案错误");
            }
        } catch (Exception e) {
            log.error("验证密保问题失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 验证邮箱验证码
     */
    @PostMapping("/verifyEmailCode")
    public Result<Void> verifyEmailCode(@RequestBody Map<String, String> request) {
        try {
            String username = request.get("username");
            String email = request.get("email");
            String emailCode = request.get("emailCode");
            
            if (username == null || email == null || emailCode == null) {
                return Result.error("参数不完整");
            }
            
            boolean isValid = userService.verifyEmailCode(username, email, emailCode);
            if (isValid) {
                return Result.success("验证成功", null);
            } else {
                return Result.error("验证码错误或已过期");
            }
        } catch (Exception e) {
            log.error("验证邮箱验证码失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 上传头像
     */
    @PostMapping("/uploadAvatar")
    public Result<Map<String, String>> uploadAvatar(@RequestParam("avatar") MultipartFile file,
                                                   HttpServletRequest request) {
        try {
            // 调试信息
            log.info("收到头像上传请求");
            log.info("Authorization头: {}", request.getHeader("Authorization"));
            log.info("Content-Type: {}", request.getContentType());
            log.info("文件大小: {}", file.getSize());
            log.info("文件名: {}", file.getOriginalFilename());
            
            // 从request中获取用户ID（由拦截器设置）
            Long userId = (Long) request.getAttribute("userId");
            log.info("从request获取的userId: {}", userId);
            
            if (userId == null) {
                log.error("userId为null，可能是拦截器没有正确设置");
                return Result.error("未提供有效的认证token");
            }
            
            // 上传头像文件
            String avatarUrl = fileService.uploadAvatar(file);
            
            // 更新用户头像信息
            userService.updateUserAvatar(userId, avatarUrl);
            
            Map<String, String> result = new HashMap<>();
            result.put("avatarUrl", avatarUrl);
            return Result.success("头像上传成功", result);
        } catch (IllegalArgumentException e) {
            log.error("头像上传参数错误", e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("头像上传失败", e);
            return Result.error("头像上传失败");
        }
    }
} 